#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "ohos_init.h"
#include "box_control.h"

//定义按键引脚
#define BUTTON_F1_GPIO 5

/**
 * @brief 初始化按键
 *
 */
static void Init_Button(void)
{
    //初始化F1按钮为输入,上拉方式
    IoTGpioInit(BUTTON_F1_GPIO);
    IoTGpioSetFunc(BUTTON_F1_GPIO, IOT_GPIO_FUNC_GPIO_5_GPIO);
    IoTGpioSetDir(BUTTON_F1_GPIO, IOT_GPIO_DIR_IN);
    IoTGpioSetPull(BUTTON_F1_GPIO, IOT_GPIO_PULL_UP);
}

/**
 * @brief 按钮线程初始化
 *
 */
static void Button_Task(void)
{
    Init_Button();

    int btn_pressed = 0;
    int last_pressed_time = 0;

    while (1) {
        /* 读取按键的电平值*/
        IotGpioValue F1Value;
        IoTGpioGetInputVal(BUTTON_F1_GPIO, &F1Value);

        //如果按键没按下但是检测到低电平
        if (F1Value == IOT_GPIO_VALUE0) {
            usleep(20 * 1000); //延迟20ms,消抖
            IoTGpioGetInputVal(BUTTON_F1_GPIO, &F1Value);
            if (F1Value == IOT_GPIO_VALUE0) {
                if (btn_pressed == 0) {
                    btn_pressed = 1;
                    motor_speed(1);
                    last_pressed_time = time(NULL); //记录按键按下时间
                }
            }
        } else {
            if (btn_pressed == 1) {
                time_t elapsed_time = time(NULL) - last_pressed_time;
                if (elapsed_time >= 10) {
                    btn_pressed = 0; //重置按键状态
                    motor_speed(0); //停止电机
                }
            }
        }

        usleep(10 * 1000); //扫描周期
    }
}

/**
 * @brief 按钮线程初始化
 *
 */
static void Button_Task_Init(void)
{
    osThreadAttr_t attr;

    attr.name = "Button_Task";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024;
    attr.priority = 15;

    if (osThreadNew((osThreadFunc_t)Button_Task, NULL, &attr) == NULL) {
        printf("Failed to create Button_Task!\n");
    }
}

APP_FEATURE_INIT(Button_Task_Init);